/*
 * @Author: your name
 * @Date: 2021-12-10 17:43:21
 * @LastEditTime: 2021-12-24 18:13:01
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \starlight_cat\src\utils\scroll-to.js
 */
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d / 2
  if (t < 1) {
    return (c / 2) * t * t + b
  }
  t--
  return (-c / 2) * (t * (t - 2) - 1) + b
}

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function () {
  return (
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function (callback) {
      window.setTimeout(callback, 1000 / 60)
    }
  )
})()

/**
 * Because it's so fucking difficult to detect the scrolling element, just move them all
 * @param {number} amount
 */
function move(amount, target) {
  document.querySelector(target).scrollTop = amount
  document.documentElement.scrollTop = amount
  document.body.parentNode.scrollTop = amount
  document.body.scrollTop = amount
}

function position(target) {
  return document.querySelector(target).scrollTop
  // return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
}

function toPosition(selector) {
  if (typeof selector === 'number') return selector
  return (
    document.querySelector(selector) || {
      offsetTop: 0,
    }
  ).offsetTop
}

/**
 * @param {number|String} to
 * @param {number} duration
 * @param {number} offset
 * @param {String} target
 * @param {Function} callback
 */
export function scrollTo({
  to = 0,
  duration = 500,
  target = '.app-main-scrollbar',
  offset = 0,
  callback = () => {},
}) {
  const start = position(target)
  const change = toPosition(to) - start + offset
  const increment = 20
  let currentTime = 0
  duration = typeof duration === 'undefined' ? 500 : duration
  var animateScroll = function () {
    // increment the time
    currentTime += increment
    // find the value with the quadratic in-out easing function
    var val = Math.easeInOutQuad(currentTime, start, change, duration)
    // move the document.body
    move(val, target)
    // do the animation unless its over
    if (currentTime < duration) {
      requestAnimFrame(animateScroll)
    } else {
      if (callback && typeof callback === 'function') {
        // the animation is done so lets callback
        callback()
      }
    }
  }
  animateScroll()
}
